<!DOCTYPE html>
<html lang="ch">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="../../reset.css" />
    <link rel="stylesheet" href="./02.使用防抖.css" />
  </head>

  <body>
    <input type="text" class="ipt" />
    <button>搜索</button>
    <div class="search_list">
      <ul></ul>
    </div>
    <script>
      let xhr = new XMLHttpRequest();

      console.log("a");

      function debounce(func, num, timer) {
        // let timer = null
        return function (...arr) {
          clearTimeout(timer);
          timer = setTimeout(() => {
            func.apply(this, arr);
          }, num);
        };
      }

      function search() {
        let productSearchAPI = `http://localhost:8888/goods/list?search=${oIpt.value}`;
        xhr.open("Get", productSearchAPI);
        xhr.send();
        xhr.onload = function () {
          if (xhr.status == 200) {
            let obj = JSON.parse(xhr.responseText);
            console.log(obj);

            let str = "";
            obj.list.forEach((v) => {
              v;
              str += `<li>${v.title}</li>`;
            });
            document.querySelector("ul").innerHTML = str;
            console.log("我打印了东西");
          }
        };
      }

      var timer = null;
      var aim = debounce(search, 600, timer);

      var oIpt = document.querySelector(".ipt");
      oIpt.oninput = () => {
        document.querySelector("ul").innerHTML = "";
        console.log("我第一次清空");
        if (oIpt.value == "") {
          document.querySelector("ul").innerHTML = "";
          console.log("我判断条件清空");
        } else {
          aim();
          clearTimeout(timer);
        }
      };
    </script>
  </body>
</html>
